package com.beemans.common.utils

import android.content.Context
import android.os.Parcelable
import com.blankj.utilcode.util.Utils
import com.tencent.mmkv.MMKV
import com.tiamosu.fly.integration.gson.GsonFactory

/**
 * @author tiamosu
 * @date 2021/3/13
 *
 * 描述：用于替代 SP 存储
 */
object MmkvHelper {

    var mmkv: MMKV? = null
        get() = field ?: MMKV.defaultMMKV(MMKV.MULTI_PROCESS_MODE, null).also { field = it }

    /**
     * SharedPreferences 迁移
     */
    fun importFromSharedPreferences(spName: String, mode: Int = Context.MODE_PRIVATE) {
        val sp = Utils.getApp().getSharedPreferences(spName, mode)
        mmkv?.importFromSharedPreferences(sp)
        sp.edit().clear().apply()
    }

    fun putString(key: String, value: String?) {
        mmkv?.encode(key, value)
    }

    fun getString(key: String, defaultVal: String? = null): String? {
        return mmkv?.decodeString(key, defaultVal)
    }

    fun putInt(key: String, value: Int) {
        mmkv?.encode(key, value)
    }

    fun getInt(key: String, defaultVal: Int = 0): Int {
        return mmkv?.decodeInt(key, defaultVal) ?: defaultVal
    }

    fun putBool(key: String, value: Boolean) {
        mmkv?.encode(key, value)
    }

    fun getBool(key: String, defaultVal: Boolean = false): Boolean {
        return mmkv?.decodeBool(key, defaultVal) ?: defaultVal
    }

    fun putLong(key: String, value: Long) {
        mmkv?.encode(key, value)
    }

    fun getLong(key: String, defaultVal: Long = 0L): Long {
        return mmkv?.decodeLong(key, defaultVal) ?: defaultVal
    }

    fun putDouble(key: String, value: Double) {
        mmkv?.encode(key, value)
    }

    fun getDouble(key: String, defaultVal: Double = 0.0): Double {
        return mmkv?.decodeDouble(key, defaultVal) ?: defaultVal
    }

    fun putByteArray(key: String, value: ByteArray?) {
        mmkv?.encode(key, value)
    }

    fun getByteArray(key: String, defaultVal: ByteArray): ByteArray? {
        return mmkv?.decodeBytes(key, defaultVal)
    }

    fun putParcelable(key: String, value: Parcelable) {
        mmkv?.encode(key, value)
    }

    fun <T : Parcelable> getParcelable(key: String, cls: Class<T>): T? {
        return mmkv?.decodeParcelable(key, cls)
    }

    fun putStringSet(key: String, value: Set<String>) {
        mmkv?.encode(key, value)
    }

    fun getStringSet(key: String): Set<String>? {
        return mmkv?.decodeStringSet(key)
    }

    /**
     * 保存数据
     */
    fun putAny(key: String, any: Any?) {
        any ?: return
        val str = GsonFactory.toJson(any)
        mmkv?.encode(key, str)
    }

    /**
     * 获取数据
     */
    inline fun <reified T> getAny(key: String): T? {
        return getString(key)?.let {
            GsonFactory.fromJson(it)
        }
    }
}